package lgs.hm.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import lgs.hm.model.Book;

@Controller
@RequestMapping("book")
@SessionAttributes(names= {"bookssss"},types= {ArrayList.class})  //找到key为books的放到session作用域里面
public class BookController {
	//logger日志，logger for java
	private Logger logger = LoggerFactory.getLogger(BookController.class);
	
	private static List<Book> books = new ArrayList<>();
	
	{
		books.add(new Book("神雕侠侣", 78.8, "金庸"));
		books.add(new Book("绝代双骄", 45.4, "古龙"));
		books.add(new Book("隋唐英雄传", 34.8, "黄金"));
	}
	
	@GetMapping("all")
	public String findAll(Map<String, Object> map) {  
		//debug  调试  使用的是debug级别，4个都会打印
		//info 信息      使用的是info级别，包括info3个都会打印
		//warning 警告   2个
		//error 错误      1个
		logger.error("这就是我写出的日志");
		
		
		//通过Map往jsp里面注入数据，等价于request.setAttribute(name,value)
		map.put("books", books);
		return "bs/books";
	}
	
	
	@GetMapping("del")
	public String del(@RequestParam("name") String name,Book book) {
		//@RequestParam("name")表示从网页上的那个参数进来，那后再传给name；
		books.remove(book);//大多情况下通过实体类
		return "redirect:all";  //删除之后用重定向到查询方法
		                         //等价于：sendRedirect()
	}
	
	@GetMapping("upd")
	public String update(@RequestParam("name1") String name1,
			@RequestParam("name")String name, @RequestParam("price") double price, @RequestParam("auth") String auth){
		int i = books.indexOf(new Book(name1,0,null));
		books.set(i, new Book(name, price, auth));
		return "redirect:all";  //response.sendRedirect()
	}
	
	@GetMapping("add")
	public String add(
			@RequestParam("name")String name, @RequestParam("price") double price, @RequestParam("auth") String auth) {
		books.add(new Book(name,price,auth));
		return "redirect:all";
	}

}
